package com.didispace;

import com.didispace.exception.DiyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "normal-error";
    public static final String RUNTIME_ERROR_VIEW = "runtime-error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ModelAndView runtimeExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exptype", "runtime");
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(RUNTIME_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = DiyException.class)
    @ResponseBody
    public Map diyExceptionJsonHandler(HttpServletRequest req, Exception e) throws Exception {
        Map<String,Object> mav = new HashMap();
        mav.put("exptype", "DiyException");
        mav.put("exception", e.getMessage());
        mav.put("url", req.getRequestURL());
        return mav;
    }
}
